package com.huaxiafinance.management.service.impl;

import com.google.common.collect.Maps;
import com.huaxiafinance.management.dto.request.LoginDto;
import com.huaxiafinance.management.dto.request.QueryRoleDto;
import com.huaxiafinance.management.dto.request.UpdateUserPasswordDto;
import com.huaxiafinance.management.mapper.*;
import com.huaxiafinance.management.model.*;
import com.huaxiafinance.management.service.UserService;
import com.huaxiafinance.management.util.*;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service("userServiceImpl")
public class UserServiceImpl implements UserService {

	private static final Logger log = Logger.getLogger(UserServiceImpl.class);

	@Autowired
	private UserMapper userMapper;

	@Autowired
	private UserRoleMapper userRoleMapper;

	@Autowired
	private RoleMapper roleMapper;
	
	@Autowired
	private OrgUserMapper orgUserMapper;
	@Autowired
	private YfqImgMapper yfqImgMapper;

	@Transactional
	@Override
	public MessageResult login(LoginDto dto, final HttpSession session, HttpServletResponse response) throws Exception {
		MessageResult messageResult = new MessageResult();

		 String code = (String) session.getAttribute(dto.getCaptcha());
		 String code1 = code;
		 if (!code1.equalsIgnoreCase(dto.getCaptchaCode())) {
			 log.error("图形验证码错误");
			 messageResult.setResultMessage(ServiceCode.CAPTCHA_ERROR);
			 return messageResult;
		 }

		User user = null;

		try {
			user = userMapper.login(dto.getUserName());
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			messageResult.setResultMessage(ServiceCode.EXCEPTION_ERROR);
			return messageResult;
		}

		if (user == null) {
			messageResult.setResultMessage(ServiceCode.USER_LOGIN_FAIL);
			return messageResult;
		} else {
			String passwrod = DesUtil.encrypt(dto.getPassword(), user.getSalt());

			if (passwrod.equals(user.getPassword())) {
				Cookie cookie = new Cookie("token", TokenUtil.converToToken(user.getCellphone()));
				cookie.setMaxAge(60 * 60 * 24 * 365 * 14);
				cookie.setDomain("huaxiafinance.com");
				cookie.setPath("/");
				response.addCookie(cookie);

				session.setAttribute("token", TokenUtil.converToToken(user.getCellphone()));
				session.setMaxInactiveInterval(60*60);//以秒为单位
				response.setHeader("token", TokenUtil.converToToken(user.getCellphone()));

				UserExample example = new UserExample();
				example.createCriteria().andCellphoneEqualTo(user.getCellphone());
				user.setLoginCount(user.getLoginCount() + 1);
				user.setLastVisit(new Date());
				userMapper.updateByExampleSelective(user, example);
				
				List<Permission> pList = userMapper.permissionList(user.getUserId());
				Integer isDesensitization=userRoleMapper.selectIsDesensitization(user.getUserId());
				if(isDesensitization==null){
					isDesensitization=1;
				}
				Map<String, Object> map = Maps.newHashMap();
				map.put("user", user);
				map.put("permissions", pList);
				map.put("isDesensitization",isDesensitization);
				map.put("token",TokenUtil.converToToken(user.getCellphone()));
				messageResult.setData(map);
				messageResult.setResultMessage(ServiceCode.SUCCESS);
			} else {
				messageResult.setResultMessage(ServiceCode.USER_LOGIN_FAIL_PASSWORD);
			}
		}
		return messageResult;
	}

	@Transactional
	@Override
	public MessageResult addUser(User user) throws Exception {
		MessageResult messageResult = new MessageResult();
		
		int i = 0;
		try {
			i = userMapper.insertNew(user);

			for (int roleId : user.getRoleId()) {
				UserRole ur = new UserRole();
				ur.setUserId(user.getUserId());
				ur.setRoleId(roleId);
				userRoleMapper.addUserRole(ur);
			}
				
			OrgUser orgUser = new OrgUser();
			orgUser.setUserId(user.getUserId());
			orgUser.setOrgCode(user.getOrgCode());
			orgUserMapper.insert(orgUser);

			
		}catch (DuplicateKeyException e) {
			messageResult.setResultMessage(ServiceCode.USER_CELLPHONE_EXIST);
			log.error(ServiceCode.DICT_CODE_DUPLICATE);
		}catch (Exception e) {
			messageResult.setResultMessage(ServiceCode.EXCEPTION_ERROR);
			log.error(e.getMessage(), e);
		}

		if (i > 0)		
			messageResult.setResultMessage(ServiceCode.SUCCESS);
		
		return messageResult;
	}

	@Transactional
	@Override
	public boolean delUser(Integer id) throws Exception {
		int i = 0;
		
		try {
			userRoleMapper.delUserRole(id);
			
			OrgUserExample example = new OrgUserExample();
			example.createCriteria().andUserIdEqualTo(id);
			orgUserMapper.deleteByExample(example);
				
			i = userMapper.deleteByPrimaryKey(id);

		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}

		return i > 0;
	}

	@Transactional
	@Override
	public boolean updUser(User user) throws Exception {
		int i = 0;
		int j = 0;
		int k = 0;
		try {
			i = userMapper.updateByPrimaryKeySelective(user);
			if (i > 0) {
				j = userRoleMapper.delUserRole(user.getUserId());

				if (j > 0) {
					for (int roleId : user.getRoleId()) {
						UserRole ur = new UserRole();
						ur.setUserId(user.getUserId());
						ur.setRoleId(roleId);
						k = userRoleMapper.addUserRole(ur);
					}
					
					if (k > 0) {
						OrgUserExample example = new OrgUserExample();
						example.createCriteria().andUserIdEqualTo(user.getUserId());
						
						OrgUser orgUser = new OrgUser();
						orgUser.setOrgCode(user.getOrgCode());
						orgUserMapper.updateByExampleSelective(orgUser, example);
					}
				}
			}
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
		return k > 0;
	}

	@Override
	public boolean addUserRole(UserRole userRole) throws Exception {
		int i = 0;

		try {
			i = userRoleMapper.addUserRole(userRole);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}

		return i > 0;
	}

	@Override
	public boolean updateUserRole(UserRole userRole) throws Exception {
		int i = 0;
		int j = 0;

		try {
			i = userRoleMapper.delUserRole(userRole.getUserId());

			if (i > 0)
				j = userRoleMapper.updateUserRole(userRole);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}

		return j > 0;
	}

	@Override
	public List<UserRole> queryUserRole(Integer id) throws Exception {

		try {
			return userMapper.queryUserRole(id);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}

		return Collections.emptyList();
	}

	@Override
	public List<Role> queryRole() throws Exception {
		try {
			return roleMapper.roleList();
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
		return Collections.emptyList();
	}

	@Override
	public List<User> queryUser(QueryRoleDto dto) throws Exception {
		dto.setPage(dto.getPage() * dto.getRows());
		
		try {
			return userMapper.queryUser(dto);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
		return Collections.emptyList();
	}

	@Override
	public User beforUpdateUser(Integer id) throws Exception {
		try {
			return userMapper.beforUpdateUser(id);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
		return null;
	}

	@Override
	public boolean updatePassword(UpdateUserPasswordDto dto) throws Exception {
		int i = 0;

		UserExample example = new UserExample();
		example.createCriteria().andUserNameEqualTo(dto.getUserName());
		User user = new User();
		try {
			user.setUserName(dto.getUserName());
			user.setPassword(dto.getPasswordNew());
			DesUtil.entryptPassword(user);
			i = userMapper.updateByExampleSelective(user, example);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}

		return i > 0;
	}
	
	@Override
	public User selectSaleMan(String userName) throws Exception {
		try {
			return userMapper.selectSaleMan(userName);
		} catch (Exception e) {
			log.error(e.getMessage());
		}
		
		return null;
	}

	@Override
	public List<YfqImg> queryUserImg(String orderNo) {
		List<YfqImg> list=yfqImgMapper.queryUserImg(orderNo);
		for(YfqImg img:list){
			img.setImgUrl(QiNiuUtil.getUrl1(img.getImgUrl()));
		}
		return list;
	}

	@Override
	public int countUser(QueryRoleDto dto) throws Exception {
		dto.setPage(null);
		try {
			return userMapper.queryUser(dto).size();
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
		return 0;
	}
}